package com.qs.redis.redisson;

import com.qs.redis.utils.RedissonClientUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 测试Redisson提供的分布式重入锁（使用多线程模拟多进程）
 *
 * @author qinyupeng
 * @since 2019年12月13日15:29:50
 */
public class TestRedissonLock {

    public static void main(String[] args) {
        RedissonClient redissonClient = RedissonClientUtils.getInstance();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        //获取重入锁
        RLock lock = redissonClient.getLock("goods");
        Task task = new Task(lock, countDownLatch);
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(task, "Thread-" + i);
        }

        for (Thread thread : threads) {
            thread.start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //等待所有线程执行完，关闭redissonClient
        redissonClient.shutdown();
    }


    static class Task implements Runnable {
        private RLock lock;
        private CountDownLatch countDownLatch;

        public Task(RLock lock, CountDownLatch countDownLatch) {
            this.lock = lock;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println("线程-" + Thread.currentThread().getName() + "-获取到了锁。。");
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("线程-" + Thread.currentThread().getName() + "-开始释放锁。。");
                countDownLatch.countDown();
                lock.unlock();
            }
        }
    }
}
